package com.innovation.ic.sc.web.controller;

import com.alibaba.fastjson.JSON;
import com.innovation.ic.b1b.framework.manager.ThreadPoolManager;
import com.innovation.ic.b1b.framework.util.StringUtils;
import com.innovation.ic.sc.base.handler.sc.MenuHandler;
import com.innovation.ic.sc.base.handler.sc.ModelHandler;
import com.innovation.ic.sc.base.pojo.constant.HttpHeader;
import com.innovation.ic.sc.base.pojo.constant.handler.RedisStorage;
import com.innovation.ic.sc.base.pojo.variable.AuthenticationUser;
import com.innovation.ic.sc.base.pojo.variable.ServiceResult;
import com.innovation.ic.sc.base.pojo.variable.ApiResult;
import com.innovation.ic.sc.base.service.ServiceHelper;
import com.innovation.ic.sc.base.service.erp9_pvestandard.ProductsService;
import com.innovation.ic.sc.base.service.sc.*;
import com.innovation.ic.sc.base.service.sc_data.InitMyCompanyService;
import com.innovation.ic.sc.base.value.DyjInterfaceAddressConfig;
import com.innovation.ic.sc.base.value.FilterParamConfig;
import com.innovation.ic.sc.base.value.RedisParamConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 抽象controller
 */
public abstract class AbstractController {

    /********************************************* helper ********************************************/
    @Autowired
    protected ServiceHelper serviceHelper;

    /********************************************* service ********************************************/
    @Autowired
    protected UploadFileService uploadFileService;

    @Autowired
    protected MyCompanyService myCompanyService;

    @Autowired
    protected ErpMyCompanyNameService erpMyCompanyNameService;

    @Autowired
    protected ActionMessageService actionMessageService;

    @Autowired
    protected AdvantageBrandService advantageBrandService;

    @Autowired
    protected MenuTreeService menuTreeService;

    @Autowired
    protected RoleService roleService;

    @Autowired
    protected UserService userService;

    @Autowired
    protected UserLoginLogService userLoginLogService;

    @Autowired
    protected SmsInfoService smsInfoService;

    @Autowired
    protected AdvantageModelService advantageModelService;

//    @Autowired
//    protected AdvantageBrandService advantageBrandService;

    @Autowired
    protected LoginService loginService;

    @Autowired
    protected InventoryService inventoryService;

    @Autowired
    protected ClientService clientService;

    @Autowired
    protected PersonnelManagementService personnelManagementService;

    @Autowired
    protected LadderPriceInfoService ladderPriceInfoService;

    @Autowired
    protected MapUserRoleService mapUserRoleService;

//    @Autowired
//    protected LadderPriceConfigService ladderPriceConfigService;

    @Autowired
    protected BrandService brandService;

    @Autowired
    protected ProductService productService;

    @Autowired
    protected DepartmentService departmentService;

    @Autowired
    protected DictionariesService dictionariesService;

    @Autowired
    protected UserManagementService userManagementService;

    @Resource
    protected InitMyCompanyService initMyCompanyService;

    @Resource
    protected ProductsService productsService;

    /********************************************* handler ********************************************/
    @Autowired
    protected ModelHandler modelHandler;

    @Autowired
    protected MenuHandler menuHandler;

    /********************************************* manager ********************************************/
    @Autowired
    protected ThreadPoolManager threadPoolManager;

    /********************************************* config ********************************************/
    @Autowired
    protected RedisParamConfig redisParamConfig;

    @Autowired
    protected FilterParamConfig filterParamConfig;

//    @Autowired
//    protected DyjInterfaceAddressConfig dyjInterfaceAddressConfig;

    /**
     * hystrix默认处理方法
     * 其它应用调用超时时调用此方法进行异常信息抛出，防止出现长时间接口不返回结果的情况出现
     *
     * @return 返回熔断默认结果
     */
    protected ResponseEntity<ApiResult> defaultFallback() {
        ApiResult apiResult = new ApiResult();
        apiResult.setSuccess(Boolean.FALSE);
        apiResult.setCode(HttpStatus.REQUEST_TIMEOUT.value());
        apiResult.setResult(Boolean.FALSE);
        apiResult.setMessage(ServiceResult.TIME_OUT);
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 将AuthenticationUser对象存储到redis中，key为token，value是json字符串
     *
     * @param authenticationUser
     */
    protected void setAuthenticationUser(AuthenticationUser authenticationUser) {
        serviceHelper.getRedisManager().set(RedisStorage.TOKEN_PREFIX + authenticationUser.getToken(), JSON.toJSONString(authenticationUser));
        serviceHelper.getRedisManager().expire(RedisStorage.TOKEN_PREFIX + authenticationUser.getToken(), redisParamConfig.getTokenTimeout());
    }

    /**
     * 从redis中根据token获取AuthenticationUser对
     *
     * @param request
     */
    protected AuthenticationUser getAuthenticationUser(HttpServletRequest request) {
        String token;
        String header = request.getHeader(filterParamConfig.getToken());
        if (StringUtils.isEmpty(header)) {
            return null;
        } else {
            String[] headerArray = header.split(HttpHeader.TOKEN_SPLIT);
            if (null == headerArray || headerArray.length != 2) {
                return null;
            } else {
                token = headerArray[1];
                Object tokenObject = serviceHelper.getRedisManager().get(RedisStorage.TOKEN_PREFIX + token);
                if (null == tokenObject) {
                    return null;
                }
                return JSON.parseObject(tokenObject.toString(), AuthenticationUser.class);
            }
        }
    }

    /**
     * 删除redis中的token
     *
     * @param request
     */
    protected void removeAuthenticationUser(HttpServletRequest request) {
        String token;
        String header = request.getHeader(filterParamConfig.getToken());
        if (StringUtils.isEmpty(header)) {
            return;
        } else {
            String[] headerArray = header.split(HttpHeader.TOKEN_SPLIT);
            if (null == headerArray || headerArray.length != 2) {
                return;
            } else {
                token = headerArray[1];
                serviceHelper.getRedisManager().del(RedisStorage.TOKEN_PREFIX + token);
            }
        }
    }


    /**
     * @Description: 获取用户ID
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2023/1/616:24
     */
    protected String getUserId(HttpServletRequest request) {
        // 获取登陆用户
        AuthenticationUser authenticationUser = getAuthenticationUser(request);
//        if (null == authenticationUser) {
//            throw new RuntimeException("登陆用户为空");
//        }
        return authenticationUser.getId();
    }
}